package day01;

import template.JdbcTemplate;
import util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class TestJDBC4 {

    private static JdbcTemplate jdbcTemplate;

    static {
        jdbcTemplate=new JdbcTemplate();
    }



    public static void main(String[] args) throws Exception {






        // insert();

        // update();

        // delete();

        // select();

        // selectById(3);

        selectByName("abc");

        // selectByName("aaa' or '1'='1");
    }






    public static void insert(){

        String sql=new StringBuffer()
                .append("insert into t_user ")
                .append("    (name) ")
                .append("values ")
                .append("    (?) ")
                .toString();
        jdbcTemplate.update(sql,"eee");
    }

    public static void update(){

        String sql=new StringBuffer()
                .append("update t_user ")
                .append("set name=? ")
                .append("where id=? ")
                .toString();
        jdbcTemplate.update(sql,"abc",4);
    }

    public static void delete(){

        String sql=new StringBuffer()
                .append("delete from t_user ")
                .append("where id=? ")
                .toString();
        jdbcTemplate.update(sql,4);
    }

    public static void select(){

        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .toString();
        List<User> users=jdbcTemplate.query(sql,new UserRowMapper());

        for (User user : users) {
            System.out.println(user.getId()+"\t"+user.getName());
        }

    }

    public static void selectById(int id){

        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .append("where id=? ")
                .toString();

        User user=jdbcTemplate.query(sql,new UserResultSetExtractor(),id);
        System.out.println(user.getId());
        System.out.println(user.getName());
    }


    public static void selectByName(String name){

        String sql=new StringBuffer()
                .append("select * ")
                .append("from t_user ")
                .append("where name=? ")
                .toString();

        List<User> users=jdbcTemplate.query(sql,new UserRowMapper(),name);

        for (User user : users) {
            System.out.println(user.getId()+"\t"+user.getName());
        }
    }


}
